package com.credithc.fastdfs.monitor.service.impl;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.csource.common.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.credithc.fastdfs.api.entity.Alarm;
import com.credithc.fastdfs.api.entity.Storage;
import com.credithc.fastdfs.api.mapper.AlarmMapper;
import com.credithc.fastdfs.monitor.config.SystemConfig;
import com.credithc.fastdfs.monitor.service.AlarmInformService;

@Service("alarmInformServiceImpl")
public class AlarmInformServiceImpl implements AlarmInformService {
	
	private static final Logger log = LoggerFactory.getLogger(AlarmInformServiceImpl.class);

	@Autowired
	private AlarmMapper alarmMapper;

	@Override
	public void inform(Storage storage) throws IOException, MyException {
		List<Alarm> alarmList = alarmMapper.selectValidAlarmList();
		for (Alarm alarm : alarmList) {
			if (validEmailAndPhone(alarm) && validFreq(alarm)) { // 校验Email和手机是否都为空,本次是否应该提醒
				String alarmMessage = validAlarm(storage, alarm);
				if(StringUtils.isNotBlank(alarmMessage)) { //满足触发告警条件
					if(StringUtils.isNotBlank(alarm.getAlarmEmail())) { //Email方式发送告警信息
						log.info(storage.getIpAddr() + " 告警触发Email方式发送 " +alarm.getAlarmEmail()+ " : [ " + alarmMessage + " ]..............");
					}
					if(StringUtils.isNotBlank(alarm.getAlarmPhone())) { //手机方式发送告警消息
						log.info(storage.getIpAddr() + " 告警触发Phone方式发送 " +alarm.getAlarmPhone()+ " : [ " + alarmMessage + " ]..............");
					}
					alarm.setAlarmLastAlertTime(new Date());
					int b = alarmMapper.updateAlarmLastAlertTime(alarm);
				}
			}
		}
	}
	
	/** 
	 * @Title: getValueByKey 
	 * @Description: 通过属性名返回结果
	 * @param 
	 * @return String
	 * @throws 
	 */ 
	private String getValueByKey(Storage storage, String key) {
		key = key.replaceFirst(key.substring(0, 1), key.substring(0, 1)
				.toUpperCase());// 首字母大写
		Method method;
		String s = null;
		try {
			method = storage.getClass().getDeclaredMethod("get" + key);// 获取对应get方法
			s = String.valueOf(method.invoke(storage));// 获得返回值
		} catch (Exception e) {
			s = null;
		}
		return s;
	}
	
	/** 
	 * @Title: validAlarm 
	 * @Description: 提取告警规则,并校验,返回是否应该告警提醒
	 * @param 
	 * @return String
	 * @throws 
	 */ 
	private String validAlarm(Storage storage, Alarm alarm) {
		String expre = alarm.getAlarmRule();
		expre = StringUtils.replace(expre, " ", "");
		String[] rules = expre.split(",");
		StringBuilder sb = new StringBuilder();
		for(String rule : rules) {
			if(rule.indexOf(">") > -1) {
				String key = rule.split(">")[0];
				String value = rule.split(">")[1];
				String realString = getValueByKey(storage, key);
				if(StringUtils.isNotBlank(realString)) {
					long realValue = Long.valueOf(realString);
					long setValue = Long.valueOf(value);
					if(realValue > setValue) { //满足条件 设置告警信息
						sb.append("触发告警 : " + rule + " 请及时处理, ");
					}
				}
			}
			if(rule.indexOf("<") > -1) {
				String key = rule.split("<")[0];
				String value = rule.split("<")[1];
				String realString = getValueByKey(storage, key);
				if(StringUtils.isNotBlank(realString)) {
					long realValue = Long.valueOf(realString);
					long setValue = Long.valueOf(value);
					if(realValue < setValue) { //满足条件 设置告警信息
						sb.append("触发告警 : " + rule + " 请及时处理, ");
					}
				}
				
			}
		}
		return sb.toString();
	}
	
	/**
	 * @Title: validEmailAndPhone
	 * @Description: 校验Email和手机，如果都为空 则返回false 不进行提醒检查
	 * @param
	 * @return boolean
	 * @throws
	 */
	private boolean validEmailAndPhone(Alarm alarm) {
		if (StringUtils.isBlank(alarm.getAlarmEmail())
				&& StringUtils.isBlank(alarm.getAlarmPhone())) {
			return false;
		}
		return true;
	}
	
	/** 
	 * @Title: validFreq 
	 * @Description: 校验提醒频率 本次是否应该提醒
	 * @param 
	 * @return boolean
	 * @throws 
	 */ 
	private boolean validFreq(Alarm alarm) {
		if(alarm.getAlarmLastAlertTime() == null) {
			return true;
		} else {
			Date lastFreqTime = alarm.getAlarmLastAlertTime();//上次提醒时间
			Date date = null;
			if(alarm.getAlarmFreq().equals(SystemConfig.ALARM_FREQ_HOURS)) { //小时提醒
				date = new Date();
				if(date.getTime() - lastFreqTime.getTime() < 60 * 60 * 1000) {//本次提醒时间距离上次不到一小时
					return false;
				}
			}
			if(alarm.getAlarmFreq().equals(SystemConfig.ALARM_FREQ_DAY)) { //天提醒
				date = new Date();
				if(date.getTime() - lastFreqTime.getTime() < 24 * 60 * 60 * 1000) {//本次提醒时间距离上次不到24小时
					return false;
				}
			}
		}
		return true;
	}

}
